package com.sync.syncmasterdata.customer.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sync.syncmasterdata.customer.entity.bip.BipCustomerEntity;
import com.sync.syncmasterdata.customer.entity.bip.BipIdocnTrastForCustomerEntity;
import com.sync.syncmasterdata.customer.pojo.CrmCustomer;
import com.sync.syncmasterdata.customer.pojo.bip.CustomerAssign;
import com.sync.syncmasterdata.customer.pojo.bip.CustomerForBip;
import com.sync.syncmasterdata.customer.pojo.bip.CustomerForBipUpdate;
import com.sync.syncmasterdata.customer.repository.biprep.BipCustomerIdcontrastRepository;
import com.sync.syncmasterdata.customer.repository.biprep.BipCustomerRepository;
import com.sync.syncmasterdata.customer.service.convert.CrmToBip;
import com.sync.syncmasterdata.dingrobot.service.DingRobotService;
import com.sync.syncmasterdata.pubdomain.BipResponse;
import com.sync.syncmasterdata.util.BipRequestUtil;
import com.sync.syncmasterdata.util.NormalUtil;
import com.sync.syncmasterdata.util.RandomCodeUtil;
import lombok.extern.slf4j.Slf4j;
import nccloud.open.api.auto.token.itf.IAPIUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Objects;

/**
 * Bip系统 客户相关服务
 * 使用步骤
 * 1.调用新增方法.
 * 2.get客户Code
 * 3.调用分配
 * 4.如果需要特殊配置再调用相应方法
 * todo:客户的controller层需要完善
 */
@Service
@Slf4j
public class BipCustomerServiceImpl {

    @Autowired
    private BipRequestUtil bipRequestUtil;

    @Autowired
    private BipCustomerRepository bipCustomerRepository;

    @Autowired
    private BipCustomerIdcontrastRepository bipCustomerIdcontrastRepository;

    @Autowired
    private DingRobotService dingRobotService;

    @Autowired
    private CrmToBip crmToBip;

    private String ACCESSTOKEN;

    /**
     * 请求新增bip 客户信息
     * @param customer
     */
    public String addCustomer(CustomerForBip customer) {
        try {
            IAPIUtils iapiUtils= bipRequestUtil.getAPIUtil();
            String url = "nccloud/api/uapbd/customermanage/customer/add";
            iapiUtils.setApiUrl(url);
            this.ACCESSTOKEN = iapiUtils.getToken();
            String params = JSONObject.toJSONString(NormalUtil.assembleMap("ufinterface",customer));
            String ret = iapiUtils.getAPIRetrun(this.ACCESSTOKEN, params);
            JSONObject retJson = JSONObject.parseObject(ret);
            if (retJson.getBoolean("success")) {
                JSONObject innerJson = retJson.getJSONObject("data").getJSONObject("ufinterface");
                if (innerJson.getString("successful").equals("Y")) {
                    JSONObject _array = (JSONObject)innerJson.getJSONArray("sendresult").get(0);
                    log.info("BIP客户添加成功");
                    return _array.getString("content");
                }else{
                    dingRobotService.simpleDingSendMsg("推送Bip客户信息（新增）出错：" + ret,new String[]{"15267167276"});
                    log.info("请求新增bip 客户信息失败,报文打印" +ret);
                }
            }else{
                dingRobotService.simpleDingSendMsg("推送Bip客户信息（新增）出错：" + ret,new String[]{"15267167276"});
                log.info("请求新增bip 客户信息失败" + ret);
            }
        } catch (Exception e) {
            e.printStackTrace();
            dingRobotService.simpleDingSendMsg("推送Bip客户信息（新增）出错：" + e.toString(),new String[]{"15267167276"});
            return null;
        }
        return null;
    }

    /**
     * 获取客户Code 使用PKCustomer值  因为返回Json中只有ID.没有code
     * @param pkCustomr
     * @return
     */
    public String getCustomerCode(String pkCustomr) {
        String entity=bipCustomerRepository.getCustomerEntity(pkCustomr);
        if (StringUtils.isNotBlank(entity)) {
            return entity;
        }
        return null;
    }

    /**
     * 客户分配
     * @param customers 客户code,单一
     * @param orgs 分配组织,数组
     * @return
     */
    public boolean assignCustomer(String customers,String[] orgs){
        try {
            IAPIUtils iapiUtils= bipRequestUtil.getAPIUtil();
            String url="nccloud/api/uapbd/customermanageext/customer/assign";
            iapiUtils.setApiUrl(url);
            CustomerAssign.AssignData assignData=CustomerAssign.AssignData.builder().customer(Arrays.asList(customers)).org(Arrays.asList(orgs)).build();
            CustomerAssign customerAssign=CustomerAssign.builder().data(assignData).build();
            String params = JSONObject.toJSONString(NormalUtil.assembleMap("ufinterface",customerAssign));
            String ret = iapiUtils.getAPIRetrun(this.ACCESSTOKEN, params);
            BipResponse<String> bipResponse = JSONObject.parseObject(ret, BipResponse.class);
            if(bipResponse.getSuccess()){
                return true;
            }else{
                dingRobotService.simpleDingSendMsg("推送Bip客户信息后分配（新增）出错：",new String[]{"15267167276"});
                return false;
            }
        } catch (Exception e) {
            log.info("推送客户分配异常");
            dingRobotService.simpleDingSendMsg("推送Bip客户信息后分配（新增）出错："+e.toString(),new String[]{"15267167276"});
            return false;
        }
    }

    //以下为更新客户信息区域
    /**
     * 先处理数据
     * @param crmCustomer crm客户信息
     */

    public boolean handleUpdateCustomerData(CrmCustomer crmCustomer) {
        //先检查 crm客户是否bip中存在
        String crmCode = crmCustomer.getNew_num();
        BipCustomerEntity customerEntity=bipCustomerRepository.getCustomerEntityByCode(crmCode);
        if (Objects.isNull(customerEntity)) {
            //信息查询不存在 todo:考虑新建bip客户资料
            return false;
        }
        //客户对象存在 计划需要修改
        String pk_customer = customerEntity.getPk_customer();
        //查询id对比表中是否存在pk值 取fileId
        BipIdocnTrastForCustomerEntity idocnTrastEntity=bipCustomerIdcontrastRepository.getTrastId(pk_customer);
        String fileId = null;
        if (Objects.isNull(idocnTrastEntity)) {
            //插入fileId
            String pkId = RandomCodeUtil.generateRandomCode();
            BipIdocnTrastForCustomerEntity idEntity = new BipIdocnTrastForCustomerEntity();
            idEntity.setFile_id(pk_customer);
            idEntity.setPk_bill(pk_customer);
            idEntity.setPk_idcontra(pkId);
            idEntity.setTs(NormalUtil.getNowDataTime());
            //执行插入操作
            bipCustomerIdcontrastRepository.addCustomerEntityByCode(idEntity);
            //赋值
            fileId = pk_customer;
        }else{
            fileId = idocnTrastEntity.getFile_id();
        }
        //转换更新对象
        CustomerForBipUpdate customerForBipUpdate = crmToBip.convertFunUpdate(crmCustomer, fileId);
        updateCustomer(customerForBipUpdate);
        //更新完成
        log.info("bip客户更新完成");
        return true;
    }

    /**
     * 请求更新bip 客户信息
     * @param customer
     */
    public void updateCustomer(CustomerForBipUpdate customer) {
        try {
            IAPIUtils iapiUtils= bipRequestUtil.getAPIUtil();
            String url = "nccloud/api/uapbd/customermanage/customer/update";
            iapiUtils.setApiUrl(url);
            this.ACCESSTOKEN = iapiUtils.getToken();
            String params = JSONObject.toJSONString(NormalUtil.assembleMap("ufinterface",customer));
            String ret = iapiUtils.getAPIRetrun(this.ACCESSTOKEN, params);
            JSONObject retJson = JSONObject.parseObject(ret);
            if (retJson.getBoolean("success")) {
                JSONObject innerJson = retJson.getJSONObject("data").getJSONObject("ufinterface");
                if (innerJson.getString("successful").equals("Y")) {
                    JSONObject _array = (JSONObject)innerJson.getJSONArray("sendresult").get(0);
                    log.info("BIP客户更新成功");
                }else{
                    dingRobotService.simpleDingSendMsg(" 更新Bip客户信息（新增）出错：" + ret,new String[]{"15267167276"});
                    log.info("请求更新bip 客户信息失败,报文打印" +ret);
                }
            }else{
                dingRobotService.simpleDingSendMsg("更新Bip客户信息（新增）出错：" + ret,new String[]{"15267167276"});
                log.info("请求更新bip 客户信息失败" + ret);
            }
        } catch (Exception e) {
            e.printStackTrace();
            dingRobotService.simpleDingSendMsg("更新Bip客户信息（新增）出错：" + e.toString(),new String[]{"15267167276"});
        }
    }

}
